package cc.vv.baselibrary.activity.components.videoshooting.activty;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

import cc.vv.baselibrary.R;
import cc.vv.baselibrary.activity.UtimingBaseActivity;
import cc.vv.baselibrary.activity.components.videoshooting.shoot.JCameraLisenter;
import cc.vv.baselibrary.activity.components.videoshooting.shoot.JCameraView;
import cc.vv.baselibrary.activity.components.videoshooting.shoot.ShootResultKey;
import cc.vv.baselibrary.global.BTResultCode;
import cc.vv.lkbasecomponent.util.LKPermissionUtil;
import cc.vv.lklibrary.log.LogOperate;

import static android.os.Build.VERSION_CODES.KITKAT;


/**
 * 照片拍摄/视频录制界面
 *
 * @author hsl
 */
public class ShootActivity extends UtimingBaseActivity {
    //权限申请自定义码
    private final int GET_PERMISSION_REQUEST = 100;
    public static final String SHOOT_TYPE = "shoot";
    private JCameraView jCameraView;
    private boolean granted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //强制竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_shoot_layout);
        jCameraView = (JCameraView) findViewById(R.id.jcameraview);
        try {
            int shoot = getIntent().getIntExtra("shoot", 0);
            //拍照
            if (1 == shoot) {
                jCameraView.setFeatures(JCameraView.BUTTON_STATE_ONLY_CAPTURE);
                //摄像
            } else if (2 == shoot) {
                jCameraView.setFeatures(JCameraView.BUTTON_STATE_ONLY_RECORDER);
            } else {
                jCameraView.setFeatures(JCameraView.BUTTON_STATE_BOTH);
            }
        } catch (Exception e) {
            LogOperate.e(e.getMessage(), e);
        }

        //设置视频保存路径
//        File file = PathUtil.getInstance().getVideoPath();
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
        if (file != null) {
            jCameraView.setSaveVideoPath(file.toString());
        } else {
            finish();
        }

        //JCameraView监听
        jCameraView.setJCameraLisenter(new JCameraLisenter() {
            @Override
            public void captureSuccess(Bitmap bitmap) {//拍照返回
                //获取图片bitmap
                File file = saveBitmap(bitmap);
                Intent intent = new Intent();
                if (file != null) {
                    intent.putExtra(ShootResultKey.IMAGEPATH, file.getAbsolutePath());
                }
                //返回数据
                setResult(BTResultCode.ShootActivity_RESULT_CODE, intent);
                finish();
            }

            //拍摄返回
            @Override
            public void recordSuccess(String url, Bitmap firstFrame) {
                File file = saveBitmap(firstFrame);
                int duration = getVideoDuration(url);
                Intent intent = new Intent();
                //视频路径
                intent.putExtra(ShootResultKey.VIDEOPATH, url);
                if (file != null) {
                    //视频预览图路径
                    intent.putExtra(ShootResultKey.THUMBPATH, file.getAbsolutePath());
                }
                //视频时长
                intent.putExtra(ShootResultKey.VIDEOLENGTH, duration);
                setResult(BTResultCode.ShootActivity_RESULT_CODE, intent);
                finish();
            }

            @Override
            public void quit() {
                //退出按钮
                ShootActivity.this.finish();
            }
        });

        //6.0动态权限获取
        getPermissions();
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        super.initView(bundle);
    }

    /**
     * 获取视频文件时长
     */

    private int getVideoDuration(String mUri) {
        String duration = null;
        android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();

        try {
            if (mUri != null) {
                HashMap<String, String> headers = null;
                if (headers == null) {
                    headers = new HashMap<String, String>();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            }

            duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
        } catch (Exception ex) {
        } finally {
            mmr.release();
        }
        if (!TextUtils.isEmpty(duration)) {
            return Integer.parseInt(duration) / 1000;
        } else {
            return 0;
        }

    }

    /**
     * 将图片保存到指定路径
     *
     * @param bitmap
     */
    private File saveBitmap(Bitmap bitmap) {
        File file = null;
        //判断sd卡是否正常
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // 获取SDCard指定目录下
//            File imagePath = PathUtil.getInstance().getImagePath();
            File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
            //如果不存在，那就建立这个文件夹
            if (!imagePath.exists()) {
                imagePath.mkdirs();
            }
            // 在SDcard的目录下创建图片文,以当前时间为其命名
            file = new File(imagePath, System.currentTimeMillis() + ".jpg");
            FileOutputStream out = null;

            try {
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            } catch (FileNotFoundException e) {
                LogOperate.e(e.getMessage(), e);
            }
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                LogOperate.e(e.getMessage(), e);
            }
        } else {
            Toast.makeText(this, "请检查您的sd卡是否可用", Toast.LENGTH_SHORT).show();
        }
        return file;
    }

    @Override
    protected void onStart() {
        super.onStart();
        //全屏显示
        if (Build.VERSION.SDK_INT >= KITKAT) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        } else {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(option);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onResume() {
        super.onResume();
        LKPermissionUtil.permission(Manifest.permission.CAMERA).request();
        boolean isCarma = LKPermissionUtil.isGranted(Manifest.permission.CAMERA);
        if (granted && isCarma) {
            jCameraView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        jCameraView.onPause();
    }

    /**
     * 获取权限
     */
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean sd = LKPermissionUtil.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            boolean audio = LKPermissionUtil.isGranted(Manifest.permission.RECORD_AUDIO);
            boolean camera = LKPermissionUtil.isGranted(Manifest.permission.CAMERA);
            if (sd && audio && camera) {
                granted = true;
            } else {
                //不具有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(ShootActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA}, GET_PERMISSION_REQUEST);

                granted = false;
            }
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == GET_PERMISSION_REQUEST) {
            int size = 0;
            if (grantResults.length >= 1) {
                int writeResult = grantResults[0];
                //读写内存权限
                //读写内存权限
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;
                if (!writeGranted) {
                    size++;
                }
                //录音权限
                int recordPermissionResult = grantResults[1];
                boolean recordPermissionGranted = recordPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!recordPermissionGranted) {
                    size++;
                }
                //相机权限
                int cameraPermissionResult = grantResults[2];
                boolean cameraPermissionGranted = cameraPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!cameraPermissionGranted) {
                    size++;
                }
                if (size == 0) {
//                    granted = true;
                    jCameraView.onResume();
                } else {
                    Toast.makeText(this, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("module", "社交");
        hashMap.put("function", "相机");
        super.onBackPressed();
    }
}
